package com.huan.drools;

import lombok.extern.slf4j.Slf4j;
import org.drools.core.event.DebugProcessEventListener;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.definition.type.FactType;
import org.kie.api.event.rule.DebugAgendaEventListener;
import org.kie.api.event.rule.DebugRuleRuntimeEventListener;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * drools 测试类
 */
@Slf4j
public class DroolsTypeDeclareApplication {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        KieServices kieServices = KieServices.get();
        KieContainer kieContainer = kieServices.getKieClasspathContainer();
        KieSession kieSession = kieContainer.newKieSession("type-ksession");
        kieSession.addEventListener(new DebugRuleRuntimeEventListener());
        kieSession.addEventListener(new DebugAgendaEventListener());
        kieSession.addEventListener(new DebugProcessEventListener());

        KieBase kieBase = kieContainer.getKieBase("type-kabse");
        FactType productOrderFactType = kieBase.getFactType("rules", "ProductOrder");
        // 此处的FactType的真实类型是EnumClassDefinition,可以获取到枚举中构造方法的参数的值
        FactType orderStatusFactType = kieBase.getFactType("rules", "OrderStatus");

        // 获取drools中枚举的值
        Class<?> factClass = orderStatusFactType.getFactClass();
        Method method = factClass.getMethod("valueOf", String.class);
        Object pay = method.invoke(null, "PAY");

        Object instance = productOrderFactType.newInstance();

        ProductItem item = new ProductItem();
        item.setItemName("iphone 13");

        productOrderFactType.set(instance, "orderId", 20220517121212001L);
        productOrderFactType.set(instance, "createdTime", new Date());
        productOrderFactType.set(instance, "item", item);
        productOrderFactType.set(instance, "orderStatus", pay);
        productOrderFactType.set(instance, "userId", 1001L);

        kieSession.insert(instance);
        kieSession.fireAllRules();

        Object orderStatus = productOrderFactType.get(instance, "orderStatus");
        log.info("获取rule中修改之后的枚举字段的值:[{}]", orderStatus);

        kieSession.dispose();
    }
}
